import { debounce } from '@/utils/helper.js';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { ScrollView, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import GiftCardBackground from '../giftCardBackground';
import ListEnd from '../giftCardDetail/listEnd';
import './index.scss';

const GiftCardItem = ({ id, cardName, backgroundContent, backgroundType }) => {
  const goToRecharge = () => {
    Taro.navigateTo({ url: `/giftCardSubPack/giftCardRecharge/index?id=${id}` });
  };

  return (
    <View className="gift-card-item" onClick={goToRecharge}>
      <GiftCardBackground className="logo" {...{ backgroundContent, backgroundType }} />

      <View className="bottom">
        <View className="name">{cardName}</View>
      </View>
    </View>
  );
};

const GiftCardShop = ({ dispatch, loading, giftCardList, giftCardFinished }) => {
  useShowLoading(loading, ['giftCard/fetchGiftCardList']);

  // 获取我的提货券列表
  const getNextList = () => {
    return dispatch({
      type: 'giftCard/fetchGiftCardList',
      payload: { pageSize: 10 },
    });
  };

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !giftCardFinished && giftCardList?.length > 0 && getNextList();
  }, 500);

  // 获取我的提货券列表
  useEffect(() => {
    getNextList();
  }, []);

  return (
    <>
      <ScrollView className="giftCardShop" enableFlex scrollY onScrollToLower={handleScrollToLower}>
        <View className="header">
          <View className="head-1">购买提货券</View>

          <View className="head-2">（选择券面输入金额）</View>
        </View>

        <View className="gift-card-list">
          {giftCardList?.map((item) => {
            return <GiftCardItem key={item.id} {...item}></GiftCardItem>;
          })}

          {giftCardFinished && giftCardList?.length > 8 && <ListEnd />}
        </View>
      </ScrollView>
    </>
  );
};
export default connect(({ loading, giftCard }) => ({
  loading,
  giftCardList: giftCard.giftCardList,
  giftCardFinished: giftCard.giftCardFinished,
}))(GiftCardShop);
